# import sys
# sys.path.append('../../')
# print(sys.path)
import json
import os
from typing import Dict, Any

import numpy as np
from utils.logger import get_logger
from .mfcc_infer import MFCCInfer
# from core import Predictor
from addict import Dict as ADict

logger = get_logger()


class MFCCPredictor:
    def __init__(self, cfg: Dict):
        self.cfg = ADict(cfg)
        self.model = MFCCInfer()

    def __call__(self, batch: Dict[str, Any]) -> Dict:
        task_id = batch['task_id']
        # s3_prefix = f's3://{self.bucket_name}'
        # batch["meta_path"] = f"{s3_prefix}/meta/{task_id}-{batch['noid']}.json"
        batch["meta_path"] = os.path.splitext(batch['path'])[0] + "-meta.json"
        try:
            if batch["embedding_progress"] == "completed":
                return batch
            batch["embedding_progress"] = "processing"
            logger.info(f"start embedding for audio {batch['path']}")
            # saved_path = self.generate_name(batch['path'], ".npy")
            embedding_saved_path = os.path.splitext(batch['path'])[0] + ".npy"
            silent_points_path = os.path.splitext(batch['path'])[0] + "-silent.npy"
            prediction, silent_points = self.model(batch['path'])
            logger.info("upload npy ...")
            # embedding_saved_path = (f'{s3_prefix}/embedding/'
            #                         f'{task_id}/{saved_path}')
            # self.storage.put_npy(prediction, embedding_saved_path)
            np.save(embedding_saved_path, prediction)
            np.save(silent_points_path, silent_points)
            batch["embedding_saved_path"] = embedding_saved_path
            batch["silent_points_path"] = silent_points_path
            batch["embedding_progress"] = "completed"
            batch["duration"] = prediction.shape[0]
            logger.info(f"embedding for audio {batch['path']} completed")
        except:
            import traceback
            error_info = traceback.format_exc()
            logger.error(f"error occurs in audio embedding: {error_info}")
            batch["embedding_progress"] = "failed"
            batch["embedding_saved_path"] = None
            batch["silent_points_path"] = None
            batch["duration"] = None
        batch['update_status'] = 'embedding'
        with open(batch["meta_path"], "w", encoding="utf-8") as f:
            json_data = json.dumps(batch, indent=4, ensure_ascii=True)
            f.write(json_data)
        return batch
